package com.nxy.cpfsfe.busi.bolag;

import com.adtec.starring.datapool.CompSDO;
import com.adtec.starring.datapool.EPOper;
import com.adtec.starring.exception.BaseException;
import com.adtec.starring.struct.dta.DtaInfo;
import com.adtec.starring.util.SpringUtil;
import com.nxy.cpfsfe.enumtype.*;
import com.nxy.cpfsfe.mybatis.mapper.TbAMapper;
import com.nxy.cpfsfe.mybatis.mapper.TsPCmdMapper;
import com.nxy.cpfsfe.mybatis.pojo.TbA;
import com.nxy.cpfsfe.service.CpfsService;
import com.nxy.cpfsfe.util.RpcCommUtil;
import com.nxy.cpfsfe.util.XmlUtil;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.sql.Timestamp;
import java.util.Date;
import java.util.Map;


public class NCSRevsRespSrvBean implements  CpfsService {
	
	@Override
	public void doService() {
		nCSRevsRespBean();
	}
    
    private final static Logger LOGGER = LoggerFactory.getLogger(NCSRevsRespSrvBean.class);  
    SqlSession sqlSession = null;   
    
    public void nCSRevsRespBean() {
    	try {
	        String tpId = DtaInfo.getInstance().getTpId();
	        sqlSession = (SqlSession) SpringUtil.getBean("mybatisSqlSession");       
	        // 获取输入
	        CompSDO inputSdo = (CompSDO) EPOper.getCompSDO(tpId, "ReqBody"); // 获取输入接口     
	        // 业务报文         
	        String bizMsg = (String) inputSdo.getValue("BizMsg")!=null?(String) inputSdo.getValue("BizMsg"):"";
	        LOGGER.info("接收到输入BizMsg报文数据：[{}]" ,bizMsg);	  
	        Map<String, Object> map = xml2BizMap(bizMsg);
            //判断是否为NPS.301.001.01报文
            if(MsgCdOrTpEnum.MSGCD_301.getCode().equals((String)map.get("/transaction/header/msg/msgCd"))){
                LOGGER.info("开始NCS冲正回执[{}]处理确认",MsgCdOrTpEnum.MSGCD_301.getCode());
                judgeOrgnlInstrId(sqlSession, map, bizMsg); 
            }
        } catch (Throwable e) {
            throw e;

        }
    }
    
    /**
     * 更新账务流水表和支付流水表
     * @param sqlSession
     * @param map
     * @param bizMsg
     */
    public void judgeOrgnlInstrId(SqlSession sqlSession, Map<String, Object> map, String bizMsg){

        try{         
            TbA tbA = queryOrgAgSeq(sqlSession, map);
            if(tbA != null){
                map.put("updTm", new Timestamp(new Date().getTime()));
                map.put("revFlg", "1");
                map.put("bizSta", StatEnum.BIZSTA_FAIL.getCode());
                //更新支付流水状态
                sqlSession.getMapper(TsPCmdMapper.class).updateByMap(map);
                //更新账务流水状态
                sqlSession.getMapper(TbAMapper.class).updateByMap(map);
                LOGGER.info("更新数据成功：账务流水表Tba冲正标识revFlg：1");
                //转发给网关
                String bizSysId = tbA.getSndSysId(); //获取原交易机构
                if(!SysEcodeEnum.CPFS.getCode().equals(bizSysId)){
                    sndGW(bizSysId, bizMsg);
                }

                
            }else{
                String refSeqNb = (String) map.get("/transaction/header/msg/refSeqNb");
                String bizSysId2 = XmlUtil.getSysIdBySeqNb(refSeqNb);
                if(!SysEcodeEnum.CPFS.getCode().equals(bizSysId2)){
                    sndGW(bizSysId2, bizMsg);
                }
                LOGGER.error("查询不到原交易");
            }
        }catch (Throwable e) {
            LOGGER.error("更新数据失败：业务流水表TbA和支付流水表tsPCmd",e);
        }

    }  
    

    /**
     * 查询账务流水表
     * @param sqlSession
     * @param map
     * @return
     */
    private TbA queryOrgAgSeq(SqlSession sqlSession, Map<String, Object> map) {
        TbAMapper tbAMapper = sqlSession.getMapper(TbAMapper.class);
        TbA tbA = new TbA();
        tbA.setCpfsSeqNo((String)map.get("cpfsSeqNo"));
        tbA.setAcqOrgId((String)map.get("acqOrgId"));
        TbA tbAResult = tbAMapper.query(tbA);
        
        return tbAResult;
    }

    /**
     * 转发给网关
     * @param bizSysId
     * @param bizMsg
     */
    public void sndGW(String bizSysId,String bizMsg){
    
         String tpId = DtaInfo.getInstance().getTpId();
	     String msgCd =XmlUtil.getValByXPath(bizMsg,"/transaction/header/msg/msgCd");
		 
		 EPOper.put(tpId, "ReqBean[0].head[0].rcvAppCd", bizSysId);
   	     EPOper.put(tpId, "ReqBean[0].head[0].reqServCd", msgCd);
	     EPOper.getCompSDO(tpId, "ReqBody").setValue("BizMsg",bizMsg);
	     String rspsCd = RpcCommUtil.getInstance().rpcFeToGW(tpId, RpcOutputInfoEnum.OutputName_Pub_Cpfsgw.getCode(),RpcOutputInfoEnum.OutPutSvr_CpfsFwdThrdPrtS.getCode());	     
         LOGGER.debug("rpc调用网关301结束......");
           
       }
        
    
    /**
     * 拆解报文为map
     * @param bizMsg
     * @return
     */
    public Map xml2BizMap (String bizMsg){
        //拆解xml报文为map
    	Map<String, Object> map=null;
    	try{
		    Map xml2BizMap =XmlUtil.xml2Map(bizMsg);    
		    //把map1<String, String>转换成map<String, Object>
		    map =xml2BizMap;        
		    map.put("chlSeqNo",(String)map.get("/transaction/body/FIToFIPmtCxlReq/Assgnmt/OrgnlInstrId"));
		    map.put("cpfsSeqNo",(String)map.get("/transaction/body/FIToFIPmtCxlReq/Assgnmt/OrgnlInstrId"));
		    map.put("xSeqNo",(String)map.get("/transaction/body/FIToFIPmtCxlReq/Assgnmt/OrgnlInstrId"));
		    map.put("acqOrgId",(String)map.get("/transaction/header/msg/rcvMbrCd"));
		}catch (Throwable e){
			throw new BaseException(RespCd.NCPO0101,e,MsgCdOrTpEnum.MSGCD_301.getCode()+"报文解包异常");
		}
        return map;
    }

}
